import express from 'express';
import db from '../config/database.js';
import winston from 'winston';

const router = express.Router();

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.json()
  ),
  transports: [
    new winston.transports.Console({
      format: winston.format.simple()
    })
  ]
});

// 数据库性能监控
router.get('/performance', async (req, res) => {
  try {
    // 获取数据库健康状态
    const healthCheckResult = await db.healthCheck();

    // 获取性能统计
    const performanceStats = db.getPerformanceStats();

    // 获取数据库文件大小
    const fs = await import('fs');
    const path = await import('path');
    const { fileURLToPath } = await import('url');

    const __filename = fileURLToPath(import.meta.url);
    const __dirname = path.dirname(__filename);
    const dbPath = path.join(__dirname, '../data/endo_sight_uc.db');

    let dbSize = 0;
    try {
      const stats = fs.statSync(dbPath);
      dbSize = stats.size;
    } catch (error) {
      logger.warn('无法获取数据库文件大小:', error.message);
    }

    res.json({
      success: true,
      message: '获取数据库性能监控数据成功',
      data: {
        health: healthCheckResult,
        performance: performanceStats,
        database_size_bytes: dbSize,
        database_size_formatted: formatBytes(dbSize),
        monitoring: {
          slow_query_threshold_ms: 1000,
          max_query_time_records: 1000,
          health_check_interval_ms: 30000
        }
      }
    });

  } catch (error) {
    logger.error('获取数据库性能监控数据失败:', error);
    res.status(500).json({
      success: false,
      message: '获取数据库性能监控数据失败',
      data: null
    });
  }
});

// 重置性能统计
router.post('/performance/reset', async (req, res) => {
  try {
    db.resetPerformanceStats();

    res.json({
      success: true,
      message: '数据库性能统计已重置',
      data: {
        reset_time: new Date().toISOString()
      }
    });

  } catch (error) {
    logger.error('重置数据库性能统计失败:', error);
    res.status(500).json({
      success: false,
      message: '重置数据库性能统计失败',
      data: null
    });
  }
});

// 数据库维护
router.post('/maintenance/optimize', async (req, res) => {
  try {
    logger.info('开始数据库优化维护...');

    // 执行VACUUM操作
    await db.query('VACUUM');

    // 执行ANALYZE更新查询计划
    await db.query('ANALYZE');

    // 执行PRAGMA optimize
    await db.query('PRAGMA optimize');

    logger.info('数据库优化维护完成');

    res.json({
      success: true,
      message: '数据库优化维护完成',
      data: {
        maintenance_time: new Date().toISOString(),
        operations: ['VACUUM', 'ANALYZE', 'PRAGMA optimize']
      }
    });

  } catch (error) {
    logger.error('数据库优化维护失败:', error);
    res.status(500).json({
      success: false,
      message: '数据库优化维护失败',
      data: null
    });
  }
});

// 格式化字节数
const formatBytes = (bytes) => {
  if (bytes === 0) return '0 Bytes';

  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));

  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

export default router;